package cn.com.dcsgo.validation.validator;

import cn.com.dcsgo.validation.ElementsOf;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ElementsOf校验器
 * @author Dcsgo
 * @since 2025/9/28 13:11
 */

public class ElementsOfValidator implements ConstraintValidator<ElementsOf, Iterable<?>> {
    private Set<String> allowedValues;


    @Override
    public void initialize(ElementsOf constraintAnnotation) {
        // 将注解中的值转换为String并收集到Set中
        allowedValues = Arrays.stream(constraintAnnotation.value())
                .map(Object::toString)
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(Iterable<?> objects, ConstraintValidatorContext constraintValidatorContext) {
        if (objects == null) {
            return true;
        }
        // 当允许的元素集合不为空时，每个元素是否在允许元素集合中，不在则校验不通过
        for (Object obj : objects) {
            if (obj != null && !allowedValues.contains(obj.toString())) {
                return false;
            }
        }
        return true;
    }
}
